<script setup lang="ts">
import { commonExportListToExcel } from '@/api/common'
import { getList } from '@/api/llm/log'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'

import { usePagination } from '@/hooks/usePagination'
import useTableRowSelection from '@/hooks/useTableRowSelection'
import useDictStore from '@/store/modules/dict'
import { formatDate, omitEmptyValue } from '@/utils/common'
import Refresh from '@iconify-icons/ep/refresh'
import Search from '@iconify-icons/ep/search'
import { FormInstance } from 'element-plus'
import { isNil } from 'lodash-es'
import { computed, onMounted, reactive, ref, toRaw } from 'vue'

defineOptions({
  name: 'api-manage/list',
})

const queryParams = reactive({
  apiName: '',
  responseResult: '',
})
const searchDateRange = ref<[string, string]>(['', ''])
const searchDateRangeParams = computed(() =>
  !isNil(searchDateRange.value)
    ? {
        requestTimeBegin: searchDateRange.value[0],
        requestTimeEnd: searchDateRange.value[1],
      }
    : null
)
const { pagination, paginationParams, changePageNumber, changePageSize } = usePagination(onSearch)
const formRef = ref<FormInstance>()
const dictStore = useDictStore()
const dicts = dictStore.getDicts(
  'api_respone_result',
  'model_type'
)
const { api_respone_result, model_type } = dicts
const columns: TableColumnList = [
  {
    type: 'selection',
    width: 55,
    align: 'left',
  },
  {
    label: '调用结果',
    prop: 'responseResult',
    minWidth: 100,
    formatter({ responseResult }) {
      return api_respone_result.getLabel(responseResult)
    },
  },
  {
    label: '调用接口名称',
    prop: 'apiName',
    minWidth: 100,
  },
  {
    label: '调用接口地址',
    prop: 'apiUrl',
    minWidth: 150,
  },
  {
    label: '调用模型名称',
    prop: 'modelName',
    minWidth: 100,
  },
  {
    label: '调用模型类别',
    prop: 'modelType',
    minWidth: 100,
    formatter({ modelType }) {
      return model_type.getLabel(modelType)
    },
  },
  {
    label: '调用单位',
    prop: 'requestDept',
    minWidth: 150,
  },
  {
    label: '调用人',
    prop: 'requestPerson',
    minWidth: 100,
  },
  {
    label: '调用时间',
    prop: 'requestTime',
    minWidth: 150,
    formatter: ({ requestTime }) => formatDate(requestTime),
  },
  {
    label: '调用IP',
    prop: 'requestIp',
    minWidth: 100,
  },
  {
    label: '总耗时',
    prop: 'responseTime',
    minWidth: 100,
    formatter({ responseTime }) {
      return responseTime + 'ms'
    },
  },
  {
    label: '输入token数',
    prop: 'inputTokens',
    minWidth: 100,
    formatter({ inputTokens }) {
      return inputTokens || '/'
    },
  },
  {
    label: '输出token数',
    prop: 'outputTokens',
    minWidth: 100,
    formatter({ outputTokens }) {
      return outputTokens || '/'
    },
  },
  {
    label: '消耗总token数',
    prop: 'usedTokens',
    minWidth: 100,
    formatter({ usedTokens }) {
      return usedTokens || '/'
    },
  },
  {
    label: '失败原因',
    prop: 'failureReason',
    minWidth: 100,
    formatter({ failureReason }) {
      return failureReason || '/'
    },
  },
]
const dataList = ref([])
const loading = ref(true)

/** 查询列表 */
async function onSearch() {
  loading.value = true
  const data = await getList({
    ...omitEmptyValue({
      ...toRaw(queryParams),
      ...searchDateRangeParams.value,
    }),
    ...paginationParams.value,
  })

  dataList.value = data.rows
  pagination.total = data.total
  setTimeout(() => {
    loading.value = false
  }, 500)
}

/** 重置新增的表单  */
async function resetForm() {
  formRef.value.resetFields()
  queryParams.apiName = ''
  queryParams.responseResult = ''
  searchDateRange.value = ['', '']
  await onSearch()
}

const { selectedRows, onRowSelectionChange } = useTableRowSelection()

/** 导出按钮操作 */
function onExport() {
  const params = {
    ...queryParams,
    ...searchDateRangeParams.value,
    ids: selectedRows.value.map((item) => item.id),
  }
  commonExportListToExcel('/model/api/log/export', params)
}

onMounted(() => {
  onSearch()
})
</script>

<template>
  <div class="main table-view-layout">
    <el-form
      ref="formRef"
      :inline="true"
      :model="queryParams"
      class="bg-el-bg w-[99/100] pl-8 pt-4"
    >
      <el-form-item prop="name">
        <el-input
          v-model="queryParams.apiName"
          placeholder="请输入接口名称关键词"
          clearable
          style="width: 240px"
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item prop="searchValue">
        <el-date-picker
          v-model="searchDateRange"
          unlink-panels
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item prop="searchValue">
        <el-select
          v-model="queryParams.responseResult"
          placeholder="响应结果"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in api_respone_result"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm"> 重置 </el-button>
        <el-button type="primary" @click="onExport">导出数据</el-button>
      </el-form-item>
    </el-form>
    <PureTableBar>
      <!-- <template #buttons>
        <el-button type="primary" @click="onExport">导出数据</el-button>
      </template> -->
      <template #table>
        <pure-table
          ref="pureTableRef"
          border
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :data="dataList"
          :columns="columns"
          :pagination="pagination"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)',
          }"
          @selection-change="onRowSelectionChange"
          @page-size-change="changePageSize"
          @page-current-change="changePageNumber"
        />
      </template>
    </PureTableBar>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
